<template>
  <el-card shadow="hover" style="width: 350px">
    <template #header>
      <div class="option-header">
        <div class="option-header-content"><span>保本雪球</span></div>
        <div v-if="props.calcSuccess=='true'" class="option-header-content"><span style="color: #22bb98 ">计算成功</span></div>
        <!--        <div v-if="props.calcSuccess=='false'" class="option-header-content"><span style="color: #e53c3c">计算失败</span></div>-->
        <div v-if="props.calcSuccess=='false'" class="option-header-content">
          <el-tooltip  effect="light"  >
            <template #content> <div style="width: 280px;">
              <span style="color: #e53c3c;">{{props.errorMsg}}</span>
            </div> </template>
            <span style="color: #e53c3c">计算失败</span>
          </el-tooltip>
        </div>
        <div>
          <el-button style="background: transparent;" :disabled="cpoyWait" class="delete" @click="copy" title="复制">
            <el-icon>
              <copy-document/>
            </el-icon>
          </el-button>
          <el-button style="background: transparent;" class="delete" @click="cancel" title="关闭">
            <el-icon>
              <circle-close/>
            </el-icon>
          </el-button>
        </div>
      </div>
    </template>

    <el-form ref="formRef" :disabled="form.data.readOnly" :model="form.data" label-width="auto" size="small"
             :rules="rules">
      <div class="optionst01">
        <el-form-item label="交易方向" prop="payDirection">
          <el-radio-group v-model="form.data.payDirection" size="small" :fill="getColor()">
            <el-radio-button label="1">买入</el-radio-button>
            <el-radio-button label="-1">卖出</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标的" label-width="auto" prop="instrumentId">
          <Underlyer v-model="form.data.instrumentId" :underlyerId="form.data.instrumentId" @change="onBlurInstrumentId" :filterDate="true" ref="underlyerIdRef"/>
        </el-form-item>
        <!--合约乘数-->
        <!--      todo-->

        <el-form-item label="起始日" label-width="auto" prop="effectiveDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.effectiveDate" @blur="onBlurEffectiveDate" type="date" placeholder="">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="期限" label-width="auto" prop="term">
          <Numberinput v-model="form.data.term" append="D"/>
        </el-form-item>

        <el-form-item label="到期日" label-width="auto" prop="terminationDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.terminationDate" type="date" placeholder=""/>
        </el-form-item>

        <el-form-item label="到期支付偏移" label-width="auto" prop="paymentDaysOffset">
          <Numberinput v-model="form.data.paymentDaysOffset" append="D"/>

        </el-form-item>

        <el-form-item label="到期支付日" label-width="auto" prop="terminationDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.terminationPaymentDate"
                          type="date"
                          placeholder=""/>
        </el-form-item>


        <el-form-item label="名义本金" prop="notional">
          <InputAmount v-model:value="form.data.notional" append="元" format="#,##0.00"></InputAmount>
        </el-form-item>


        <el-form-item label="期初价格" label-width="auto">
          <el-col :span="8">
            <el-checkbox name="status" false-label="0" true-label="1" v-model="form.data.priceOnWait">待定</el-checkbox>
          </el-col>
          <el-col :span="16">
            <InputAmount v-model:value="form.data.spotPrice" :disabled="form.data.priceOnWait=='1'"
                         format="#,##0.##" append="元"/>
          </el-col>
        </el-form-item>

        <el-form-item label="交易数量" prop="optionEntitlement">
          <Numberinput v-model="form.data.optionEntitlement" precision="2"  :disabled="form.data.priceOnWait=='1'" @change="optionEntitlementChange"/>
        </el-form-item>

        <el-form-item label="返息率" label-width="auto">
          <el-col :span="8">
            <el-checkbox v-model="form.data.MarginYieldYear" name="status" false-label="0" true-label="1">年化
            </el-checkbox>
          </el-col>
          <el-col :span="16">
            <Numberinput v-model="form.data.MarginYield" precision="2" append="%"/>
          </el-col>
        </el-form-item>
      </div>
      <!---------------------------------------------- 分割线---------------------------------------------------------->
      <div class="optionst02">
        <!--        敲出方向
                敲出障碍价比例
                观察频率
                敲出票息（%）☑年化
                未触发票息（%）☑年化
                计息天数
                计息基准
                收益-->
        <el-form-item label="敲出方向" prop='cbxTriggerType'>
          <dictCombox v-model="form.data.cbxTriggerType"
                      dictType="cbxTriggerType"
                      :style="{width: '100%'}"></dictCombox>
        </el-form-item>
        <el-form-item label="敲出障碍价">
          <el-col :span="12">
            <Numberinput v-model="form.data.konckLevelPercentage"  precision="2" @blur="onBlurkonckLevelPercentage"  append="%"/>
          </el-col>
          <el-col :span="12">
            <Numberinput v-model=" form.data.konckLevel" @blur="onBlurkonckLevel" precision="2" append="元"/>
          </el-col>
        </el-form-item>
        <el-form-item label="观察频率">
          <dictCombox v-model="form.data.ObserFrequency"
                      dictType="ObserFrequency"></dictCombox>
        </el-form-item>
        <el-form-item label="敲出票息">
          <el-col :span="8">
              <el-checkbox label="年化" v-model="form.data.knockOutYieldYear" name="type" false-label="0" true-label="1">年化</el-checkbox>
          </el-col>
          <el-col :span="16">
            <Numberinput v-model="form.data.knockOutYield" :disabled="form.disabled.knockOutYield" precision="2" append="%"/>
          </el-col>
        </el-form-item>
        <el-form-item label="未触发票息">
          <el-col :span="8">
              <el-checkbox label="年化" v-model="form.data.unKnockOutYieldYear" name="type" false-label="0" true-label="1">年化</el-checkbox>
          </el-col>
          <el-col :span="16">
            <Numberinput v-model="form.data.unKnockOutYield" precision="2" append="%"/>
          </el-col>
        </el-form-item>

        <el-form-item label="计息基准" prop="daycounter" v-show="form.data.unKnockOutYieldYear=='1'||form.data.knockOutYieldYear=='1'||form.data.MarginYieldYear=='1'">
          <dictCombox v-model="form.data.daycounter" prop='disDayCount'
                      dictType="dayCounter"
                      :style="{width: '100%'}"></dictCombox>
        </el-form-item>
        <el-form-item label="收益">
          <el-button @click="observationDialogVisible = true">收益</el-button>
        </el-form-item>
        <el-dialog :title="title" v-model="observationDialogVisible" width="50%" append-to-body
                   :modal-append-to-body="false" destroy-on-close>
          <observationTable ref="observationTableRef" :data="form" :setForm="setForm" :setDisable="setDisable"/>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="proxy.$refs.observationTableRef.saveEvent();observationDialogVisible = false">确 定</el-button>
              <el-button @click="observationDialogVisible = false">取 消</el-button>
            </div>
          </template>
        </el-dialog>

        <el-form-item class="operation">
          <el-button type="primary" @click="calc" :disabled="form.data.priceOnWait=='1'">计算</el-button>
          <el-button @click="save2CalcLog" v-show="props.useType=='calc'" :disabled="form.data.priceOnWait=='1'">存为草稿</el-button>
        </el-form-item>
      </div>
    </el-form>
    <div class="optionst03">
      <PricingParam ref="PricingParamRef" :formData="form.data"  :valueDate="props.valueDate"  size="small" label-width="auto" :productType="productType"
                    :disabled="form.data.readOnly" :index="props.index"
                    :calcPricingParam="props.calcPricingParam"></PricingParam>
    </div>
    <singleResult :result="form.result" :index="props.index" ></singleResult>
  </el-card>
</template>

<script setup>
import {generateOberserDates} from '../common/common'
import {getCurrentInstance, onMounted, onUpdated, provide, reactive, ref, toRaw, toRefs, watch, nextTick} from 'vue'
import Underlyer from '../../../../../xquant/base/underlyer'
import Numberinput from '../../../../../xquant/base/number'
import InputAmount from '../../../../../xquant/base/InputAmount'
import dictCombox from '@/xquant/base/dictCombox'
import PricingParam from '@/views/calc/otcOtion/pricingparam/index'
import singleResult from '@/views/calc/otcOtion/result/single'
import observationTable from './observation'
import {getTradeDay} from '@/utils/calc'
import {isVoid, isNotVoid} from '@/utils/util'
import {getTerminationPaymentDate} from '@/api/calc/otcOption/calc'
import {getOffset} from '../../../../../api/calc/otcOption/calc'
import {debounce} from 'lodash'
import {setCommonSpotPrice} from '@/views/calc/otcOtion/instrument/common/common'
import {formartFormP4, formartTableP2, unFormartNumber, formartFormP2, numberPrecision} from '@/utils/numberUtil'
import {validateDates} from "../common/validate";

const getColor = () => {
  return form.data.payDirection == '1' ? '#E53C3C' : '#22BB98'
}
 const {proxy} = getCurrentInstance()
const productType = 'ELN_ACB_BASICSNOWBALL'
const cpoyWait = ref(false)
const labelWidth = ref('111px')
const form = reactive({
  data: {
    payDirection: '1',
    instrumentId: null,
    productType: 'ELN_ACB_BASICSNOWBALL',
    effectiveDate: proxy.$moment(new Date()).format('YYYY-MM-DD'),
    terminationDate: '',
    terminationPaymentDate: '',
    term: '30',
    paymentDaysOffset: '0',
    priceOnWait: '0',
    spotPrice: '',
    konckLevelPercentage: '100',
    konckLevel: '',
    strike: 0,
    notional: '',
    optionEntitlement: '',
    daycounter: 'Actual/365 (Fixed)',
    calendar: 'CHINA_EX',
    daycounterTerm: '365',
    isIncludeEndDate: '0',
    endDate: '',
    isIncludeStartDate: '1',
    startDate: '',
    MarginYieldYear: '1',
    MarginYield: '',
    cbxTriggerType: 'Greater',
    levelPercentage: '',
    unKnockOutYield: '',
    knockOutYield: '',
    unKnockOutYieldYear: '1',
    knockOutYieldYear: '1',
    ObserFrequency: '1M',
    knocks: [],
    effectiveDateConv: 'Following',
    terminationDateConv: 'Following',
    paymentDateConv: 'Following'
  },
  knocks:[],
  result: {},
  disabled: {
    knockOutYield: false
  },
  initFlag: ''
})
var observationDialogVisible = ref(false)
const rules = {
  payDirection: [{required: true, message: '请选择交易方向', trigger: 'change'}],
  instrumentId: [{required: true, message: ' ', trigger: 'change'}],
  effectiveDate: [{required: true, message: ' ', trigger: 'change'}],
  terminationDate: [{required: true, message: ' ', trigger: 'change'}],
  term: [{required: true, message: ' ', trigger: 'change'}],
  paymentDaysOffset: [{required: true, message: ' ', trigger: 'change'}],
  notional: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  daycounter: [{required: true, message: ' ', trigger: 'change'}],
  daycounterTerm: [{required: true, message: ' ', trigger: 'change'}],
  spotPrice: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  optionEntitlement: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  strike: [{required: true, message: ' ', trigger: 'blur'}, {
    validator: (rule, value, callback) => {
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  konckLevelPercentage: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  knockOutYield: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  paymentAmountPecentage: [{required: true, message: ' ', trigger: 'change'}],
  paymentAmount: [{required: true, message: ' ', trigger: 'change'}],
}
const save2CalcLog = () => {
  getInstrumentJson().then((res) => {
    if (Boolean(res)) props.save2CalcLog(res, props.index)
  })

}
watch(() => props.result, (nv, ov) => {
  let other = {
    'type': '保本雪球',
    '标的': computed(() => {
      if (proxy.$refs.underlyerIdRef&&proxy.$refs.underlyerIdRef.underlyerIdsList[0]) {
        return (proxy.$refs.underlyerIdRef.underlyerIdsList[0].productName+'').trim().split(' ').join(',')
      }
    }),
    '交易日期': props.valueDate,
    '合约交易方向': form.data.payDirection == '1' ? '客户卖价' :  '客户买价',
    '合约类型': form.data.optionType == 'Call' ? 'C' : 'P',
    '到期日': form.data.terminationDate,
    '数量': formartFormP2(form.data.optionEntitlement),
    '名义金额': formartFormP2(form.data.notional),
    '开仓标的价': formartFormP2(form.data.spotPrice),
    '期权单价': computed(() => {
      if (nv) {
        return formartFormP2(nv.npv / form.data.optionEntitlement)
      }
    }),
    '百分比估值': computed(() => {
      if (nv) {
        return formartFormP2(100 * nv.npv / form.data.notional)
      }
    }),
  }
  form.result = Object.assign(other, nv)
}, {immediate: true})
const onBlurkonckLevel = ()=>{
  form.data.konckLevelPercentage = form.data.konckLevel/form.data.spotPrice * 100
}

const onBlurkonckLevelPercentage = ()=>{
  form.data.konckLevel = form.data.konckLevelPercentage*form.data.spotPrice / 100
}
const getProductType = () => {
  return (proxy.$refs.underlyerIdRef.underlyerIdsList[0].productName+'')
}

watch(() => [props.cfgId,form.data.instrumentId], ([newId, oldId]) => {
  getPricingCfg()
  setTimeout(() => {
    proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }, 1000);
})

const onBlurInstrumentId = () => {
  setSpotPrice()
  getPricingCfg()
  setTimeout(() => {
    proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }, 1000);
}
watch(() => form.data.priceOnWait, (nv, ov) => {
  if (nv.length == 1) {
    form.data.spotPrice = 0
  } else {
    setSpotPrice()
  }
})
/*
* 修改状态  false:当前没有操作  true:当前在被其他方法操作
* */
const lock = reactive({
  paymentDaysOffset: false,
  terminationPaymentDate: false,
})
watch(() => form.data.paymentDaysOffset, (nv, ov) => {
  if (nv === '') return
  if (lock.terminationPaymentDate) return
  lock.terminationPaymentDate = true
  onpaymentDaysOffsetChange()
})
const onpaymentDaysOffsetChange = debounce(function () {
  getTerminationPaymentDate({
    'calDay': form.data.terminationDate,
    'offset': form.data.paymentDaysOffset
  }).then(response => {
    lock.terminationPaymentDate = false
    if (response.errorCode != 0) {

    } else {
      form.data.terminationPaymentDate = response.result.CAL_DAY
    }
  })
}, 1000)
watch(() => form.data.terminationPaymentDate, (nv, ov) => {
  if (nv == ov || nv === '') return
  if (lock.paymentDaysOffset) return
  lock.paymentDaysOffset = true
  onterminationPaymentDate()
})
const onterminationPaymentDate = debounce(function (nv, ov) {
  getOffset({
    'day': form.data.terminationPaymentDate,
    'calDay': form.data.terminationDate
  }).then(response => {
    if (response.errorCode != 0) {

    } else {
      if (response.result == null) {
        onpaymentDaysOffsetChange()
        return
      }
      form.data.paymentDaysOffset = response.result.i
      lock.paymentDaysOffset = false
    }
  })
}, 1000)
onUnmounted(() => {
  // 移除组件时，取消定时器
  onpaymentDaysOffsetChange.cancel()
  onterminationPaymentDate.cancel()
})
const onBlurTerminationDate= (nv, ov) => {
  let a = proxy.$moment(form.data.terminationDate)
  let b = proxy.$moment(form.data.terminationPaymentDate)
  form.data.paymentDaysOffset = b.diff(a, 'days')
}
watch(() => [form.data.effectiveDate, form.data.terminationDate], ([nv, n2v], [ov, o2v]) => {
  if (!proxy.lsh.isEmpty(nv) && !proxy.lsh.isEmpty(n2v)) {
    let a = proxy.$moment(n2v)
    let b = proxy.$moment(nv)
    form.data.term = Number(a.diff(b, 'days'))
   proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }
})
watch(() => [form.data.term], ([newValue], [oldValue]) => {
  if (isNotVoid(String(form.data.effectiveDate)) && isNotVoid(String(newValue))) {
    let a = proxy.$moment(form.data.effectiveDate)
    form.data.terminationDate = a.add(newValue, 'days').format('YYYY-MM-DD')
    onpaymentDaysOffsetChange()
  }
})
watch(() => [form.data.notional, form.data.spotPrice], ([nv, n2v], [ov, o2v]) => {
  if (!proxy.lsh.isEmpty(nv) && !proxy.lsh.isEmpty(n2v)) {

    form.data.optionEntitlement = String(Number(nv) / Number(n2v))
  }
})


watch(() => [form.data.notional], ([newValue], [oldValue]) => {
  if (optionEntitlementLinkValid(newValue, form.data.spotPrice, form.data.optionEntitlement)) {
    return
  }
  onBlurkonckLevelPercentage()
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.spotPrice))) {
      form.data.optionEntitlement = proxy.lsh.divide(newValue, form.data.spotPrice).toFixed(4)
      return
    }
    if (isNotVoid(String(form.data.optionEntitlement))) {
      form.data.spotPrice = proxy.lsh.divide(newValue, form.data.optionEntitlement).toFixed(4)
      return
    }
  }
})
watch(() => [form.data.spotPrice], ([newValue], [oldValue]) => {
  if (optionEntitlementLinkValid(form.data.notional, newValue, form.data.optionEntitlement)) {
    return
  }

  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.notional))) {
      form.data.optionEntitlement = proxy.lsh.divide(form.data.notional, newValue).toFixed(4)
      return
    }
    if (isNotVoid(String(form.data.optionEntitlement))) {
      form.data.notional = proxy.lsh.multiply(form.data.optionEntitlement, newValue).toFixed(4)
      return
    }
  }
})

/*计息频率监听*/
watch(() => [form.data.ObserFrequency, form.data.knockOutYield, form.data.effectiveDate, form.data.terminationDate],
    ([newFrequency,newknockOutYield],[oldFrequency,oldknockOutYield]) => {
  if (newknockOutYield==oldknockOutYield) return
  generateOberserDates(form)
})

const optionEntitlementChange = (newValue) => {
  if (form.data.priceOnWait == '1') return
  if (optionEntitlementLinkValid(form.data.notional, form.data.spotPrice, newValue)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.spotPrice))) {
      form.data.notional = proxy.lsh.multiply(newValue, form.data.spotPrice).toFixed(0)
      return
    }
    if (isNotVoid(String(form.data.notional))) {
      form.data.spotPrice = proxy.lsh.divide(form.data.notional, newValue).toFixed(4)
      return
    }
  }
}


watch(() => [form.data.spotPrice], ([newValue], [oldValue]) => {
  if (strikeLinkValid(newValue, form.data.konckLevelPercentage, form.data.strike)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.konckLevelPercentage))) {
      form.data.strike = proxy.lsh.multiply(newValue, proxy.lsh.divide(form.data.konckLevelPercentage, 100)).toFixed(4)
      return
    }
    if (isNotVoid(String(form.data.strike))) {
      form.data.konckLevelPercentage = proxy.lsh.multiply(proxy.lsh.divide(form.data.strike, newValue), 100).toFixed(4)
      return
    }
  }
})

const onStrikeChange = (newValue) => {
  let a = newValue
  if (isNotVoid(String(form.data.spotPrice))) {
    form.data.konckLevelPercentage = proxy.lsh.multiply(proxy.lsh.divide(a, form.data.spotPrice), 100)
    return
  }
}

const onkonckLevelPercentageChange = (newValue) => {
  let a = newValue
  if (isNotVoid(String(form.data.spotPrice))) {
    form.data.strike = proxy.lsh.multiply(proxy.lsh.divide(newValue, 100), form.data.spotPrice).toFixed(4)
    return
  }
}

function strikeLinkValid(spotPrice, konckLevelPercentage, strike) {
  if (isNotVoid(String(spotPrice)) && isNotVoid(String(konckLevelPercentage)) && isNotVoid(String(strike))) {
    if (proxy.lsh.isEqual(strike, proxy.lsh.multiply(proxy.lsh.divide(konckLevelPercentage, 100), spotPrice).toFixed(4))) {
      return true
    } else {
      return false
    }
  }
}


function optionEntitlementLinkValid(notional, spotPrice, optionEntitlement) {
  if (Boolean(Number(notional)) && Boolean((Number(spotPrice))) && Boolean(Number(optionEntitlement))) {
    if (proxy.lsh.isEqual(optionEntitlement, proxy.lsh.divide(notional, spotPrice).toFixed(4))) {
      return true
    } else {
      return false
    }
  }
}

watch(() => props.valueDate, (newValue, oldValue) => {
  if (newValue != oldValue) {
    setSpotPrice()
    //触发修改定价参数的价格
    proxy.$refs.PricingParamRef.setSpotPrice({
      valueDate:props.valueDate,
      instrumentId:form.data.instrumentId
    })
   proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }
})
const onBlurEffectiveDate = () => {
  form.initFlag = false
  setSpotPrice()
}
const setSpotPrice = () => {
  setCommonSpotPrice(proxy,form,props)
}

const props = defineProps({
  /*是否为重放*/
  isReCalc: {
    type: Boolean,
    default: false
  },
  calcSuccess:{
    type: String,
    default: ''
  },
  errorMsg:{
    type: String,
    default: ''
  },
  useType: {
    type: String,
    default: 'calc'
  },
  save2CalcLog: {type: Function, default: null},
  index: {
    type: String,
    default: ''
  },
  del: {
    type: Function,
    default: null
  },
  copy: {
    type: Function,
    default: null
  },
  calc: {
    type: Function,
    default: null
  },
  getDefaultCfg: {
    type: Function,
    default: null
  },
  calcPricingParam: {
    type: Object,
    default: {}
  },
  result: {
    type: Object,
    default: {}
  },
  setformData: {
    type: Function,
    default: null
  },
  formData: {
    type: Object,
    default: null
  },
  cfgId: {type: String, default: ''},
  valueDate: {type: String, default: ''}
})
const getResult = () => {
  var data = []
  for (var item in props.result) {
    if (['npv', 'delta', 'gamma', 'vega', 'theta', 'rho', 'spotPrice', 'dscRate'].includes(item)) {
      data.push({
        key: item,
        val: proxy.lsh.ceil(props.result[item], 4)
      })
    }
  }
  return data
}
//定价参数
const getPricingCfg = async () => {
  let query = {
    'calcPricingParam': {
      'cfgId': props.cfgId
    },
    'instrument': {
      'productType': 'ELN_ACB_BASICSNOWBALL',
      'termsheet': {
        'underlyerIds': [form.data.instrumentId],
        'customLegs': [{
          'legId': 'leg01',
          'productType': 'ELN_ACB_BASICSNOWBALL'
        }
        ],
        'legs': [{
          'legId': 'leg01',
          'payDirection': '1'
        }
        ]
      }
    }
  }
  //设置定价参数中的定盘价
  proxy.$refs.PricingParamRef.setSpotPrice({
    valueDate:props.valueDate,
    instrumentId:form.data.instrumentId
  })
  if (props.getDefaultCfg != null) {
    props.getDefaultCfg(query, props.index)
  }
}
const cancel = () => {
  props.del(props.index)
}
const copy = () => {
  props.copy(props.index)
  cpoyWait.value = true;
  setTimeout(() => {
    cpoyWait.value = false;
  }, 1000);
}
const getInstrumentJson = async () => {
  return new Promise((resolve) => {
    proxy.$refs['formRef'].validate(valid => {
      if (valid) {
        validateDates(form)
        let calcPriceParam = getCalcPriceParam()
        if (form.knocks.length == 0) {
          generateOberserDates(form)
        }
        let otcOption = {
          instrument: {
            'termsheet': {
              'productType': 'ELN_ACB_BASICSNOWBALL',
              'issuePrice': form.data.spotPrice,
              'payDirection': form.data.payDirection,
              'notional': form.data.notional,
              'notionalCurrency': 'CNY',
              'effectiveDate': form.data.effectiveDate,
              'effectiveDateConv': form.data.effectiveDateConv,
              'terminationDateCalendar': 'CHINA_EX',
              'effectiveDateCalendar': 'CHINA_EX',
              'margin': {
                'marginAmount': '0',
                'overLoss': '0'
              },
              'terminationDate': form.data.terminationDate,
              'terminationDateConv': form.data.terminationDateConv,
              'calendars': [
                'CHINA_EX'
              ],
              'underlyerIds': [
                form.data.instrumentId
              ],
              'underlyers': [
                {
                  'instrumentId': form.data.instrumentId
                }
              ],
              'knockOut': {
                'payDirection': form.data.payDirection,
                'observeType': 'Close',
                'observeRounding': -1,
                // 'ObservFrequency': form.data.ObserFrequency,
                'knocks': form.knocks
              },
              'unTrigger': {
                'payDirection': form.data.payDirection,
                'unTriggerType': 'NoKnockInAndNoKnockOut',
                'calclationPeriod': {
                  'startDate': form.data.effectiveDate,
                  'startDateConv': form.data.effectiveDateConv,
                  'isIncludeStartDate': form.data.isIncluded,
                  'endDate': form.data.terminationDate,
                  'endDateConv': form.data.terminationDateConv,
                  'isIncludeEndDate': form.data.isIncludeEndDate,
                  'calendar': 'CHINA_EX'
                },
                'paymentDate': form.data.paymentDate,
                'paymentDateConv': form.data.paymentDateConv,
                'minimumYields': [
                  {
                    'paymentAmount': '',
                    'paymentAmountPecentage': form.data.MarginYield / 100,
                    'daycounter': form.data.MarginYieldYear == '1' ? form.data.daycounter : '',
                    'participationRate': '1.0'
                  }
                ],
                'basicYield': {
                  'daycounter': form.data.unKnockOutYieldYear == '1' ? form.data.daycounter : '',
                  'paymentAmountPecentage': form.data.unKnockOutYield / 100,
                  'participationRate': 1
                },
                'paymentDateCalendar': 'CHINA_EX'
              },
              'rival': '',
              'memo': ''
            },
            'productType': 'ELN_ACB_BASICSNOWBALL'
          },
          calcPricingParam: {
            valueDate: props.valueDate,
            cfgId: props.cfgId,
            calcPPCode: calcPriceParam.calcPPCode,
            underlyingPricingParams: [
              {
                underlyingID: form.data.instrumentId,
                dividend: calcPriceParam.dividend,
                volSurface: calcPriceParam.volSurface,
                funding: calcPriceParam.discount,
                spotPrice: calcPriceParam.spotPrice == '0' ? '' : calcPriceParam.spotPrice,
                spotQuoteType: calcPriceParam.spotQuoteType
              }
            ],
            discount: calcPriceParam.discount
          },
          underlyingMarkets: [
            {
              'underlyingID': form.data.instrumentId,
              'fixingPrices': [],
              'observerPrices': []
            }
          ],
          customPricingParam: {
            type:calcPriceParam.calcPPCode.split('_')[1],
            routes:calcPriceParam.calcPPCode.split('_')[1]=="QD"?"256":"100000"
          }
        }
        let calcInstrumentForm = toRaw(form.data)
        let result = props.result
        let json = {
          otcOption: otcOption,
          calcInstrumentForm: calcInstrumentForm,
          calcPricingForm: calcPriceParam,
          calcResultForm: result
        }
        resolve(json)
      } else {
        resolve('')
      }
    })
  })
}
const calc = (flag) => {
  /*flag 标识 为All时单次计算不会提示成功或失败*/
  getInstrumentJson().then((res) => {
    if (Boolean(res)) {
      let otcOption = res.otcOption
      otcOption.calcInstrumentForm = res.calcInstrumentForm
      otcOption.calcPricingForm = res.calcPricingForm
      if (otcOption != '') {
        props.calc(otcOption, props.index, flag)
      }
    }
  })
}
const getCalcPriceParam = () => {
  let calcPriceParam = proxy.$refs.PricingParamRef.getCalcPricingParam()
  return calcPriceParam
}

const getFormData = () => {
  return form
}
const setForm = (data) => {
  if (data.knocks) {
    form.knocks = data.knocks
  }
  form.data.ObserFrequency  = data.data.ObserFrequency
}
defineExpose({
  calc, getPricingCfg, getCalcPriceParam, getFormData,getInstrumentJson,proxy
})
onMounted(() => {
  /*获取默认定价配置*/
  // getPricingCfg()
  /*获取预填表单*/
  form.initFlag = props.isReCalc
  if (props.formData != null) {
    form.initFlag = isNotVoid(props.calcPricingParam)
    let data = props.formData.data || props.formData
    form.data = Object.assign(form.data, data)
  }
  // 这里获取DOM的value是旧值
  nextTick(()=>{
    form.initFlag = false
  })
})
watch(() => proxy.$attrs.disabled, (nv) => {
  form.data.readOnly = nv
}, {
  immediate: true
})
const setDisable = (v) => {
  form.disabled.knockOutYield = v
}
watch(()=>form,()=>{

  proxy.$attrs.cacheFormData()
},{deep:true})
</script>
<style>

</style>

